import os
import logging
from fastapi import FastAPI, Request, Depends, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware

from models.base import Base, engine
from routes.api import api_router
from routes.web import web_router
from services import exchange_service
# 从配置文件中导入合约信息模块
from services.contract_config_adapter import get_all_symbols, get_contract_info

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 创建FastAPI应用
app = FastAPI(title="量化交易API", version="0.1.0")

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("logs/app.log"),
    ]
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# 设置模板
templates = Jinja2Templates(directory="templates")

# 注册路由
app.include_router(api_router, prefix="/api")
app.include_router(web_router)

@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化工作"""
    # 确保日志目录存在
    os.makedirs("logs", exist_ok=True)
    
    # 检查合约配置信息
    logging.info("正在检查合约配置信息...")
    symbols = get_all_symbols()
    if symbols:
        logging.info(f"合约配置加载成功，共有 {len(symbols)} 个合约")
    else:
        logging.warning("合约配置加载失败或无可用合约")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的清理工作"""
    # 关闭交易所连接
    await exchange_service.close()

@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """HTTP异常处理器"""
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail},
    )

@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """通用异常处理器"""
    logging.error(f"未捕获的异常: {exc}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={"detail": "内部服务器错误"},
    )

@app.get("/")
async def root():
    """根路由重定向到web首页"""
    return {"message": "Welcome to Quant Trading API"}

if __name__ == "__main__":
    import uvicorn
    # 从环境变量读取端口，默认为8080
    port = int(os.getenv("PORT", 8080))
    uvicorn.run("app:app", host="0.0.0.0", port=port, reload=True)
